package com.doupi.partner.util;

import ch.qos.logback.classic.Level;
import ch.qos.logback.classic.Logger;
import ch.qos.logback.classic.LoggerContext;
import ch.qos.logback.classic.spi.LoggerContextListener;
import ch.qos.logback.core.Context;
import ch.qos.logback.core.spi.ContextAwareBase;
import ch.qos.logback.core.spi.LifeCycle;
import ch.qos.logback.core.util.LocationUtil;
import ch.qos.logback.core.util.OptionHelper;

import java.net.URL;
import java.util.Properties;
import java.util.Set;

/**
 * logback启动参数监听
 */
public class LogbackPropertiesListener extends ContextAwareBase implements LoggerContextListener, LifeCycle {
	private final static String DEFAULT_PROPERTIES_FILE = "classpath:doupi-partner-util-config-debug.properties";

	private final static String PROPERTIES_ENV_KEY = "logback.properties.file";

	private final static String LOGBACK_PROPERTIES_PREFIX = "logback";

	@Override
	public boolean isResetResistant() {
		return false;
	}

	@Override
	public void onStart(LoggerContext context) {
	}

	@Override
	public void onReset(LoggerContext context) {

	}

	@Override
	public void onStop(LoggerContext context) {

	}

	@Override
	public void onLevelChange(Logger logger, Level level) {

	}

	@Override
	public void start() {
		initProperties();
	}

	private void initProperties() {
		try {
			Context context = getContext();
			String file = OptionHelper.getEnv(PROPERTIES_ENV_KEY);
			if (null == file) {
				file = OptionHelper.getSystemProperty(PROPERTIES_ENV_KEY, DEFAULT_PROPERTIES_FILE);
			}
			URL url = LocationUtil.urlForResource(file);
			Properties properties = new Properties();
			properties.load(url.openStream());
			Set<String> keys = properties.stringPropertyNames();
			for (String key : keys) {
				if (key.startsWith(LOGBACK_PROPERTIES_PREFIX)) {
					context.putProperty(key, properties.getProperty(key));
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			// ignore should never appear
		}
	}

	@Override
	public void stop() {

	}

	@Override
	public boolean isStarted() {
		return false;
	}
}
